package com.xiaohang.springstudy.chapter1.rest;

import com.xiaohang.spring.api.model.Response;
import com.xiaohang.springstudy.chapter1.domain.UserRepository;
import com.xiaohang.springstudy.chapter1.entity.UserDo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
// @RestController = @Controller + @ResponseBody
@RequestMapping("/api/v1/users")
@Slf4j
public class UserController {
    @Autowired
    private UserRepository repository;

    @ApiOperation(value = "获得所有用户信息", tags = "chapter1")
    @GetMapping(name = "获得所有用户信息", value = "/", produces = "application/json;charset=UTF-8")
    public Response getUserList() {
        log.debug("查询所有学生");
        List<UserDo> userDoList = repository.findAll();
        log.info("{}", userDoList);
        return new Response().success(true).data(userDoList);
    }

    @ApiOperation(value = "根据ID查找用户信息", tags = "chapter1")
    @GetMapping(name = "根据ID查找用户信息", value = {"/{id}/queryUserInfo"}, produces = "application/json;charset=UTF-8")
    public Response getUser(@ApiParam(name = "id", required = true, defaultValue = "1") @PathVariable(name = "id", required = true) String id) {
        return new Response().success(true).data(repository.getOne(Long.parseLong(id)));
    }

    @ApiOperation(value = "更新用户信息", tags = "chapter1")
    @PutMapping(name = "更新用户信息", value = "/", produces = "application/json;charset=UTF-8")
    public Response updateUser(@ApiParam(name = "userDo", required = true)@RequestBody UserDo userDo) {
        repository.save(userDo);
        return new Response().success(true);
    }

    @ApiOperation(value = "根据ID删除用户信息", tags = "chapter1")
    @DeleteMapping(name = "根据ID删除用户信息", value = "/{id}/delUserInfo", produces = "application/json;charset=UTF-8")
    public Response delUser(@ApiParam(name = "id", required = true) @PathVariable(name = "id") String id) {
        repository.deleteById(Long.parseLong(id));
        return new Response().success(true);
    }
}
